package com.phalanxim.dao.impl;

import com.phalanxim.dao.AddressDao;
import com.phalanxim.service.Address;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository("addressDao")
public class AddressDaoImpl implements AddressDao
{
  @Autowired
  private SessionFactory sessionFactory;

  //Address
  @Transactional(readOnly = true)
  public List<Address> getAddressList()
  {
    Session session = sessionFactory.openSession(); // not part of a transaction, so we need to open a session manually
    List<Address> addresss = session.createQuery("from Address address").list();
    session.close();
    return addresss;
  }

  @Transactional(readOnly = true)
  public Address findAddress(Long id)
  {
    Session session = sessionFactory.openSession();
    Address address = (Address) session.createCriteria(Address.class).add(Restrictions.eq("id", id)).uniqueResult();
    session.close();
    return address;
  }

  @Transactional
  public Address saveAddress(Address address)
  {
    Session session = sessionFactory.getCurrentSession();
    session.save(address);
    return address;
  }

  @Transactional
  public Address updateAddress(Address address)
  {
    Session session = sessionFactory.getCurrentSession();
    session.update(address);
    return address;
  }

  @Transactional
  public Address removeAddress(Address address)
  {
    Session session = sessionFactory.getCurrentSession();
    session.delete(address);
    return address;
  }
}
